﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mysoft.MyCM.Business
{
	/// <summary>
	/// Web Api Client 基础类型
	/// 继承类型推荐使用单例
	/// </summary>
	public abstract class BaseWebApiClientManager
	{
		#region 单例
		protected object SyncLocker = new object();

		///// <summary>
		/////  MyPkgMngPatchWCFService 单例
		///// </summary>
		//public static readonly BaseWebApiClientManager Manager = new BaseWebApiClientManager();

		/// <summary>
		/// 私有构造
		/// </summary>
		protected BaseWebApiClientManager()
		{
		}
		#endregion

		/// <summary>
		/// 设置参数
		/// </summary>
		/// <param name="baseUrl"></param>
		public void SetParams(string baseUrl)
		{
			SetParams(baseUrl, null);
		}

		/// <summary>
		/// 设置参数
		/// </summary>
		/// <param name="baseUrl"></param>
		/// <param name="appendedHeaders"></param>
		public void SetParams(string baseUrl, NameValueCollection appendedHeaders)
		{
			lock (this.SyncLocker)
			{
				M.MValidator.CheckForEmptyString("WebApi Base Url", baseUrl);
				this.ApiBaseUrl = baseUrl;
				this.AppendedHeaders = appendedHeaders;
			}
		}

		/// <summary>
		/// 获取一个经过参数设置的WebClient
		/// 请使用using块
		/// </summary>
		/// <returns></returns>
		public M.Web.WebApiClient GetClient()
		{
			lock (this.SyncLocker)
			{
				M.Web.WebApiClient client = new M.Web.WebApiClient(this.ApiBaseUrl);
				if (this.AppendedHeaders != null)
				{
					foreach (string name in this.AppendedHeaders.AllKeys)
					{
						client.AddHeader(name, this.AppendedHeaders[name]);
					}
				}
				return client;
			}
		}

		/// <summary>
		/// Api访问根地址
		/// </summary>
		public string ApiBaseUrl { get; private set; }

		/// <summary>
		/// 扩展请求头
		/// </summary>
		protected NameValueCollection AppendedHeaders = null;
	}
}
